﻿#include "mainwindow.h"

std::string log_dir = ("d:/images" + QDateTime::currentDateTime().toString("/yyyyMMdd/")).toStdString();
std::string log_filename = QDateTime::currentDateTime().toString("/yyyyMMdd").toStdString();
std::string log_extension = ".txt";
std::string full_path = log_dir + log_filename + log_extension;


std::shared_ptr<spdlog::logger> logger_data = spdlog::basic_logger_mt("custom_logger", full_path);





MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent)
{
   
    logger_data->set_pattern("%v");
	logger->flush_on(spdlog::level::info);

    logger->info("程序启动");




    bool ret =loadPara();
    if(ret == false)
    {
        QMessageBox::critical(nullptr, "para", "参数文件不存在");
        qApp->quit();
    }

	



    logger->info("串口读取");
    LightSource.ComPort  = m_settings_para->value("para/m_com_port", "COM1").toString();
    LightSource2.ComPort = m_settings_para->value("para/m_com_port2", "COM2").toString();


    bool Ret = LightSource.open();
    if(Ret != true)
    {
        QMessageBox::critical(nullptr, "error", LightSource.ComPort);
    }
    else
    {

        if(m_type_name == "9006")
        {
            const char* data="#310FF11";
            LightSource.SerialPort->write(data);
        }
        else
        {
           const char* data="#310C86A";
           LightSource.SerialPort->write(data);
        }
    }


    Ret = LightSource2.open2();
    if (Ret != true)
    {
        QMessageBox::critical(nullptr, "error", LightSource2.ComPort);
    }
    else
    {

        if(m_type_name == "9006")
        {

            QByteArray data =QByteArray::fromHex("2433313030353133");
            LightSource2.SerialPort->write(data);
        }
        else
        {
            QByteArray data =QByteArray::fromHex("2433313030323134");
            LightSource2.SerialPort->write(data);
        }
    }


    if (m_login_dialog == nullptr)
    {
        m_login_dialog = new Login_Dialog();
        m_login_dialog->setModal(true);
//        connect(m_login_dialog->m_login_button, &QPushButton::clicked, this, &MainWindow::login);
    }



    m_load_recipe_dialog.m_dir =  m_type_dir;
    m_load_recipe_dialog.setModal(true);
    connect(m_load_recipe_dialog.m_qpushbutton_load, &QPushButton::clicked, this, &MainWindow::loadRecipe);
    initMainWindow();

    QString qstring_path = m_type_dir + "/" + m_type_name + "/para.db";

    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");

    db.setDatabaseName(qstring_path);
    if (!db.open()) {
        QMessageBox::critical(nullptr, qstring_path, "SQLite open error");
    }


    //检测类初始化
    {
        m_qdialog_detection = new QDialog(this);
        m_qdialog_detection->setModal(true);
        m_tabwidget_detection = new QTabWidget(m_qdialog_detection);
        m_tabwidget_detection->move(0, 0);
        m_tabwidget_detection->setFixedSize(1920, 1000);
        for (int i = 0; i < m_camera_number; i++)
        {
            QtThreadProcess* pQtThreadProcess = new QtThreadProcess();
            pQtThreadProcess->m_camera_index = i;
            QString section = "camera" + QString::number(i) + "/";
            pQtThreadProcess->m_camera_name = m_settings_para->value(section + "m_cameraname", QString::number(i)).toString();
            pQtThreadProcess->m_detection_number = m_settings_para->value(section + "m_detection_number", 1).toInt();
            pQtThreadProcess->m_image_dir = m_settings_para->value(section + "m_image_dir", "").toString();
            


            pQtThreadProcess->m_io_camera = m_settings_para->value(section + "m_io_camera", "").toInt();
            pQtThreadProcess->m_io_finish = m_settings_para->value(section + "m_io_finish", "").toInt();
            pQtThreadProcess->m_io_result = m_settings_para->value(section + "m_io_result", "").toInt();

           connect(pQtThreadProcess, &QtThreadProcess::sendDetectionResult, this, &MainWindow::showResult, Qt::QueuedConnection);


            QString qstring_dir = m_type_dir + "/" + m_type_name  ;
            pQtThreadProcess->m_function = new Function(nullptr, qstring_dir, i);
            connect(pQtThreadProcess->m_function->m_pushbutton_return, &QPushButton::clicked, this, &MainWindow::returnMainFrame);
            m_tabwidget_detection->addTab(pQtThreadProcess->m_function, pQtThreadProcess->m_camera_name);


            m_vector_detection_thread.push_back(pQtThreadProcess);
        }
    }

    //dl_3初始化////////////////////////////////////
    dl_3_init();
    //相机类初始化
    {
        m_qdialog_camera = new QDialog(this);
        m_qdialog_camera->setModal(true);
        m_tabwidget_camera = new QTabWidget(m_qdialog_camera);
        m_tabwidget_camera->move(0, 0);
        m_tabwidget_camera->setFixedSize(1920, 1000);
        for (int i = 0; i < m_camera_number; i++)
        {


            CameraHKQDialog* p = new CameraHKQDialog(nullptr, m_settings_para, "camera" + QString::number(i));


            connect(p->m_qpushbutton_hide, &QPushButton::clicked, this, &MainWindow::returnMainFrame);
            QString section = "camera" + QString::number(i) + "/";
            p->m_camera_name = m_settings_para->value(section + "m_cameraname", QString::number(i)).toString();

            m_tabwidget_camera->addTab(p, p->m_camera_name);
            if (m_online == 1)
            {
                //在线检测
                logger->info("camera connect");
                p->m_SN = m_settings_para->value(section + "m_SN", QString::number(i)).toString();
                p->m_type = m_settings_para->value(section + "m_type", QString::number(i)).toString();
                p->m_index= i;

                bool result = p->initCamera(p->m_SN, callback, m_vector_detection_thread[i]);
                if (result == false)
                {
                    QString StringMessage = QString("相机%1连接失败").arg(i);
                    QMessageBox::information(nullptr, "相机错误", StringMessage);
                }
            }
            if (m_online == 0)
            {
                //离线检测
//                QString image_dir = m_settings_para->value(section + "m_image_dir", QString::number(i)).toString();
                QDir dir(m_vector_detection_thread[i]->m_image_dir);
                if (!dir.exists())
                {
                    QMessageBox::critical(nullptr, "Title", "离线测试文件夹不存在");
                }
                else
                {
                    dir.setFilter(QDir::Files | QDir::NoSymLinks);
                    QStringList filters;
                    filters << "*.bmp" << "*.jpg" << "*.png";
                    dir.setNameFilters(filters);

                    QStringList  string_list = dir.entryList();
                    foreach(QString  var, string_list) {
                        m_vector_detection_thread[i]->m_images_path.push_back(m_vector_detection_thread[i]->m_image_dir + "\\" + var);
                    }
                }
                QTimer* m_qtimer_offline = new QTimer(this);
                connect(m_qtimer_offline, &QTimer::timeout, this, [=]() {
                    m_vector_detection_thread[i]->m_image_index++;
                    if (m_vector_detection_thread[i]->m_images_path.size() > 0)
                    {
                        Mat image_read_file;
                        image_read_file = imread(m_vector_detection_thread[i]->m_images_path[(m_vector_detection_thread[i]->m_image_index) % m_vector_detection_thread[i]->m_images_path.size()].toLocal8Bit().toStdString());
                        if (!image_read_file.empty())
                        {
                            callback(image_read_file,m_vector_detection_thread[i]);
//                            m_vector_detection_thread[i]->m_camera_index = i;
//                            m_vector_detection_thread[i]->m_qDisplayFrameQueue.push_back(image_read_file);
                        }
                    }
                    });
                m_qtimer_offline->start(20);//固定频率读取离线测试图像
            }
            m_vector_camera.push_back(p);
        }
    }
//处理类和相机类相互关联
    for (int i = 0; i < m_camera_number; i++)
    {
        connect(m_vector_detection_thread[i], &QtThreadProcess::sendShowImage, m_vector_camera[i], &CameraHKQDialog::showImage);
        
    }


    
    //modbus
    {
        for(int i=0;i<m_camera_number;i++)
        {
            QString section = "camera" + QString::number(i) + "/";
            m_plc_trigger.push_back(m_settings_para->value(section+"m_plc_trigger",0).toInt());
            m_plc_finish.push_back(m_settings_para->value(section+"m_plc_finish",0).toInt());
            m_plc_result.push_back(m_settings_para->value(section+"m_plc_result",0).toInt());
        }

        
        m_modbus_ip = m_settings_para->value("para/m_modbus_ip", "192.168.1.88").toString();
        m_modbus_port = m_settings_para->value("para/m_modbus_port", 502).toInt();
        
        m_modbus_tcp = modbus_new_tcp(m_modbus_ip.toStdString().c_str(), m_modbus_port);
        if (m_modbus_tcp == nullptr)
            QMessageBox::information(nullptr, "", "PLC设置参数错误");
        else
        {
//            int CONNECTION_TIMEOUT =  3000;
//            modbus_set_response_timeout(m_modbus_tcp, CONNECTION_TIMEOUT / 1000, (CONNECTION_TIMEOUT % 1000) * 1000);
//            modbus_set_byte_timeout(m_modbus_tcp, CONNECTION_TIMEOUT / 1000, (CONNECTION_TIMEOUT % 1000) * 1000);

           

            if (modbus_connect(m_modbus_tcp) == -1)
            {
                QMessageBox::information(nullptr, "", "PLC连接错误");
                modbus_close(m_modbus_tcp);
                modbus_free(m_modbus_tcp);
                m_modbus_tcp = nullptr;
            }
			if (m_type_name == "9006")
			{

				uint16_t plc_write_value = 0;
				modbus_write_registers(m_modbus_tcp, 1010, 1, &plc_write_value);
			}
			else
			{
				uint16_t plc_write_value = 1;
				modbus_write_registers(m_modbus_tcp, 1010, 1, &plc_write_value);
			}
        }
		

        m_timer_plc = new QTimer(this);
        connect(m_timer_plc, &QTimer::timeout, this, &MainWindow::timerPLC);
        m_timer_plc->start(10);


    }
	//存图线程开始
		m_save_image_thread = new SaveImageThread();
	m_save_image_thread->run();
    Sleep(1000);
    startDetection();


}

MainWindow::~MainWindow()
{

    LightSource.SerialPort->close();
//    LightSource2.SerialPort->close();
    if(m_modbus_tcp != nullptr)
    {
        modbus_close(m_modbus_tcp);
		modbus_free(m_modbus_tcp);
        /*delete m_modbus_tcp;*/
    }
    logger->warn("程序关闭");
    for (int i = 0; i < m_camera_number; i++)
    {
        if(m_online==1)
            m_vector_camera[i]->m_camera_interface->camera_end();
    }

//    m_serial->quit();
}

void MainWindow::clickCamera()
{
    //          if(m_login_privilege <2)
    //          {
    //              QMessageBox::warning(nullptr, "", "用户登录权限不够");
    //              return;
    //          }
    if (m_vector_detection_thread[0]->m_proess_state == false)
    {
        for (int i = 0; i < m_camera_number; i++)
        {
            m_vector_detection_thread[i]->m_only_show_state = true;
        }
        m_qdialog_camera->show();
    }
    else
    {
        QMessageBox::warning(nullptr, "Title", "停止检测，再设置参数");
    }
}

void MainWindow::clickPara()
{
    //          if(m_login_privilege <2)
    //          {
    //              QMessageBox::warning(nullptr, "", "用户登录权限不够");
    //              return;
    //          }
    if (m_vector_detection_thread[0]->m_proess_state == false)
    {
        m_qdialog_detection->show();
        //              m_vector_detection_thread->m_function
        //              m_detection_para_tab_widget->setCurrentIndex(0);

        //              m_detection_para_tab_widget->raise();
    }
    else
    {
        QMessageBox::warning(nullptr, "", "停止检测，再设置参数");
    }
}

void MainWindow::closeEvent(QCloseEvent *event)
{
    QMessageBox::information(nullptr, "", "不能从这里退出");
    event->ignore();
}

void MainWindow::closeSoftware()
{
    int ok = QMessageBox::warning(this, ("退出!"), ("你确定退出吗？"), QMessageBox::Yes, QMessageBox::No);
    if (ok == QMessageBox::Yes)
    {
        m_settings_para->setValue("para/geometry", saveGeometry());
        m_settings_para->setValue("para/state", saveState());
        m_settings_para->sync();
        qApp->quit();
    }
}

void MainWindow::initImageControl()
{
    m_image_widget = new QWidget();
    setCentralWidget(m_image_widget);
    QGridLayout* qgridlayout = new QGridLayout();
    qgridlayout->setSizeConstraint(QLayout::SetMinAndMaxSize);
    qgridlayout->setSpacing(1);
    qgridlayout->setMargin(1);
    m_image_widget->setLayout(qgridlayout);
    int step = (m_camera_number+1)/2;
    for(int i=0;i<m_camera_number;i++)
    {
        ShowQLabel* p = new ShowQLabel(m_image_widget);
        m_vector_show_qlabel.push_back(p);
        qgridlayout->addWidget(p,i/step,i%step,1,1);
    }
}

void MainWindow::initdockDevicesizetable()
{
    m_qdockwidget_devicesizetable = new QDockWidget(("磁盘容量界面"), this);
    m_qdockwidget_devicesizetable->setObjectName("磁盘容量界面");
    m_qdockwidget_devicesizetable->setAllowedAreas(Qt::LeftDockWidgetArea|Qt::RightDockWidgetArea|Qt::BottomDockWidgetArea);
    addDockWidget(Qt::RightDockWidgetArea, m_qdockwidget_devicesizetable);
    menuBar()->addMenu(("磁盘容量界面"))->addAction(m_qdockwidget_devicesizetable->toggleViewAction());
    DeviceSizeTable* w = new DeviceSizeTable();
    m_qdockwidget_devicesizetable->setWidget(w);
}

void MainWindow::initdockPannel()
{
    m_qdockwidget_pannel = new QDockWidget(("控制面板界面"), this);
    m_qdockwidget_pannel->setObjectName("控制面板界面");
    m_qdockwidget_pannel->setAllowedAreas(Qt::LeftDockWidgetArea|Qt::RightDockWidgetArea);
    addDockWidget(Qt::LeftDockWidgetArea, m_qdockwidget_pannel);
    menuBar()->addMenu(("控制面板"))->addAction(m_qdockwidget_pannel->toggleViewAction());

    QWidget* qwidget = new QWidget();
    m_qdockwidget_pannel->setWidget(qwidget);

    QVBoxLayout* qvobxlayout = new QVBoxLayout();
    qvobxlayout->setSpacing(50);
    qwidget->setLayout(qvobxlayout);

    m_qpushbutton_start_detection = new QPushButton();
    m_qpushbutton_start_detection->setText("开始检测");
    qvobxlayout->addWidget(m_qpushbutton_start_detection);
    connect(m_qpushbutton_start_detection, &QPushButton::clicked, this, &MainWindow::startDetection);

    m_qpushbutton_stop_detection = new QPushButton();
    m_qpushbutton_stop_detection->setDisabled(true);
    m_qpushbutton_stop_detection->setText("停止检测");
    qvobxlayout->addWidget(m_qpushbutton_stop_detection);
    connect(m_qpushbutton_stop_detection, &QPushButton::clicked, this, &MainWindow::stopDetection);

    m_qpushbutton_camera = new QPushButton();
    m_qpushbutton_camera->setText("相机设置");
    qvobxlayout->addWidget(m_qpushbutton_camera);
    connect(m_qpushbutton_camera, &QPushButton::clicked, this, &MainWindow::clickCamera);

    m_qpushbutton_para = new QPushButton();
    m_qpushbutton_para->setText("检测设置");
    qvobxlayout->addWidget(m_qpushbutton_para);
    connect(m_qpushbutton_para, &QPushButton::clicked, this, &MainWindow::clickPara);

//    m_qpushbutton_open_clear = new QPushButton();
//    m_qpushbutton_open_clear->setText("清除数据");
//    qvobxlayout->addWidget(m_qpushbutton_open_clear);
//    connect(m_qpushbutton_open_clear, &QPushButton::clicked, this, [=](){
//        for(int i=0;i< m_camera_number;i++)
//        {
//           m_vector_error_number[i]=0;
//           m_vector_all_number[i]=0;
//        }
//    });


    m_qpushbutton_open_image_dir = new QPushButton();
    m_qpushbutton_open_image_dir->setText("打开图像目录");
    qvobxlayout->addWidget(m_qpushbutton_open_image_dir);
    connect(m_qpushbutton_open_image_dir, &QPushButton::clicked, this, [=](){
        QDesktopServices::openUrl(QUrl(m_settings_para->value("para/m_save_image_dir", "").toString(), QUrl::TolerantMode));
    });



    m_qpushbutton_open_type_dir = new QPushButton();
    m_qpushbutton_open_type_dir->setText("切换型号");
    qvobxlayout->addWidget(m_qpushbutton_open_type_dir);
    connect(m_qpushbutton_open_type_dir, &QPushButton::clicked, this, [=](){

        m_load_recipe_dialog.updateQListView();
        m_load_recipe_dialog.show();
    });

//    QPushButton* p = new QPushButton();
//    p->setText("登录");
//    qvobxlayout->addWidget(p);
//    connect(p, &QPushButton::clicked, this, [=](){


//    });


//    m_qpushbutton_open_help = new QPushButton();
//    m_qpushbutton_open_help->setText("上相机拍照");
//    qvobxlayout->addWidget(m_qpushbutton_open_help);
//    connect(m_qpushbutton_open_help, &QPushButton::clicked, this, [=](){
//        m_vector_camera[1]->softTrigger();
//        //QDesktopServices::openUrl(QUrl::fromLocalFile(m_para_dir + "/help.pdf"));
//    });

//    m_qpushbutton_open_help = new QPushButton();
//    m_qpushbutton_open_help->setText("相机输出信号");
//    qvobxlayout->addWidget(m_qpushbutton_open_help);
//    connect(m_qpushbutton_open_help, &QPushButton::clicked, this, [=](){
//        if(m_camera_number==4)
//        {
//            m_vector_camera[3]->m_camera_interface->setOutput(true);
//            Sleep(100);
//            m_vector_camera[3]->m_camera_interface->setOutput(false);
//        }
//    });


    m_qpushbutton_exit = new QPushButton();
    m_qpushbutton_exit->setText("退出软件");
    qvobxlayout->addWidget(m_qpushbutton_exit);
    connect(m_qpushbutton_exit, &QPushButton::clicked, this, &MainWindow::closeSoftware);

//    qvobxlayout->addStretch();
}

void MainWindow::initMainWindow()
{

    setWindowIcon(QIcon(QCoreApplication::applicationDirPath() + "/picture/logo.svg"));

    initdockPannel();
    initImageControl();

    initdockShow();
//    initdockDevicesizetable();

    restoreGeometry(m_settings_para->value("para/geometry").toByteArray());
    restoreState(m_settings_para->value("para/state").toByteArray());
}

bool MainWindow::loadPara()
{
    m_exe_directory = QCoreApplication::applicationDirPath();
    m_para_dir = m_exe_directory + "/para";
    QString path;
    path=   m_para_dir + "/para.ini";
    //创建配置文件操作对象
    m_settings_para = new QSettings(path, QSettings::IniFormat);
    m_settings_para->setIniCodec("UTF-8");
    m_save_data_dir=m_settings_para->value("para/m_save_data_dir","").toString();
    m_type_dir =  m_settings_para->value("para/m_type_dir","").toString();
    m_type_dir =  m_exe_directory + "/" + m_type_dir;
    m_type_name =  m_settings_para->value("para/m_type_name","").toString();
    m_user_passward =  m_settings_para->value("para/m_user_passward","").toString();
    m_admin_passeard =  m_settings_para->value("para/m_admin_passeard","").toString();
    m_senior_passeard= m_settings_para->value("para/m_senior_passeard","").toString();
    m_camera_number=m_settings_para->value("para/m_camera_number",1).toInt();
    m_online=m_settings_para->value("para/m_online",-1).toInt();
	m_save_image_dir = m_settings_para->value("para/m_save_image_dir", "").toString();
     setWindowTitle(m_type_name + " 2025 09 01");
    return true;
}

void MainWindow::login()
{
//    if (m_login_dialog->m_user_edit->currentText() == "user")
//    {
//        if (m_login_dialog->m_passward_edit->text() == m_user_passward)
//        {
//            m_login_privilege = 1;
//            m_login_dialog->m_state_label->setText("user 已登录");
//            m_login_dialog->hide();
//        }
//    }
//    if (m_login_dialog->m_user_edit->currentText() == "admin")
//    {
//        if (m_login_dialog->m_passward_edit->text() == m_admin_passeard)
//        {
//            m_login_privilege = 2;
//            m_Login_Dialog->m_state_label->setText("admin 已登录");
//            m_Login_Dialog->hide();
//        }
//    }
//    if (m_Login_Dialog->m_user_edit->currentText() == "senior")
//    {
//        if (m_Login_Dialog->m_passward_edit->text() == m_senior_passeard)
//        {
//            m_login_privilege = 3;
//            m_Login_Dialog->m_state_label->setText("senior 已登录");
//            m_Login_Dialog->hide();
//        }
//    }
}

void MainWindow::returnMainFrame()
{
    for (int i = 0; i < m_camera_number; i++)
    {
        m_vector_detection_thread[i]->m_only_show_state = false;
    }
    m_qdialog_camera->hide();
    m_qdialog_detection->hide();
}

void MainWindow::showResult(VectorOutputResult result)
{



        if (result.m_camera_index != 3)
        {
			if (result.m_detectin_result)
			{
				uint16_t plc_write_value = 1;
				modbus_write_registers(m_modbus_tcp, m_plc_result[result.m_camera_index], 1, &plc_write_value);
                logger->info("plc"+to_string(m_plc_result[result.m_camera_index]) +"write"+to_string(plc_write_value));
				m_vector_all_number[result.m_camera_index]++;

			}
			else
			{
                uint16_t plc_write_value = 2;
				modbus_write_registers(m_modbus_tcp, m_plc_result[result.m_camera_index], 1, &plc_write_value);
                logger->info("plc"+to_string(m_plc_result[result.m_camera_index]) +"write"+to_string(plc_write_value));
				m_vector_all_number[result.m_camera_index]++;
				m_vector_error_number[result.m_camera_index]++;
			}
        }
        else
        {
            uint16_t value = 0;
            if (m_modbus_tcp != nullptr)
                modbus_read_registers(m_modbus_tcp, m_plc_result[1], 1, &value);
            //0=orign 1=ok 2=ng
            if (value == 2)
            {
                //如果已经是错误的，不用再写结果了
                ;
            }
            else
            {
                if (result.m_detectin_result)
                {
                    uint16_t plc_write_value = 1;
                    modbus_write_registers(m_modbus_tcp, m_plc_result[result.m_camera_index], 1, &plc_write_value);
                    logger->info("plc"+to_string(m_plc_result[result.m_camera_index]) +"write"+to_string(plc_write_value));
                    m_vector_all_number[result.m_camera_index]++;

                }
                else
                {
                    uint16_t plc_write_value = 2;
                    modbus_write_registers(m_modbus_tcp, m_plc_result[result.m_camera_index], 1, &plc_write_value);
                    logger->info("plc"+to_string(m_plc_result[result.m_camera_index]) +"write"+to_string(plc_write_value));
                    m_vector_all_number[result.m_camera_index]++;
                    m_vector_error_number[result.m_camera_index]++;
                }
            }
        }

        uint16_t plc_write_value = 1  ;
        modbus_write_registers(m_modbus_tcp,m_plc_finish[result.m_camera_index],1,&plc_write_value);
        logger->info("plc"+to_string(m_plc_finish[result.m_camera_index]) +"write"+to_string(plc_write_value));

    Mat mat_show = result.m_image_draw.clone();


  

    double ratio_x =  double(m_vector_show_qlabel[result.m_camera_index]->width()) /  double(mat_show.cols) ;
    double ratio_y =  double(m_vector_show_qlabel[result.m_camera_index]->height()) /  double(mat_show.rows) ;
    double ratio_image = ratio_x < ratio_y ?  ratio_x : ratio_y;

    if(ratio_image >1)
    {
        ratio_image =1;
    }
    else
    {
        cv::resize(mat_show, mat_show, Size(mat_show.cols * ratio_image , mat_show.rows * ratio_image));
    }


    QImage Qtempimage = matToQImage(mat_show);


    QString message_show2;
    if(result.m_detectin_result == true)
    {
        message_show2 = "OK";
    }
    else
    {
        message_show2 = "NG";
    }
////    logger->info(m_vector_camera_name[result.m_camera_index].toStdString() + ":plc and show time" + to_string(m_time_use) + "ms");
    QString message_show  =  result.m_camera_name + QString(":序号%1 检测时间%2ms").arg(result.m_detection_index).arg(result.m_time_use);
    message_show2  +=  result.m_messgae;


    if (!Qtempimage.isNull())
    {
        if(result.m_detectin_result)
            m_vector_show_qlabel[result.m_camera_index]->loadtextimage(Qtempimage,message_show + message_show2 ,Qt::green);
        else
            m_vector_show_qlabel[result.m_camera_index]->loadtextimage(Qtempimage,message_show + message_show2 ,  Qt::red);
    }
	m_vector_show_qlabel[result.m_camera_index]->draw(Qtempimage);
	result.m_image_draw = QImageToCvMat(Qtempimage);

	saveImage(result);

}

void MainWindow::startDetection()
{

    for (int i = 0; i < m_camera_number; i++)
    {
        m_vector_detection_thread[i]->m_proess_state = true;



    }
    m_qpushbutton_start_detection->setDisabled(true);
    m_qpushbutton_stop_detection->setDisabled(false);
}

void MainWindow::stopDetection()
{
    for (int i = 0; i < m_camera_number; i++)
    {
        m_vector_detection_thread[i]->m_proess_state = false;
    }
    m_qpushbutton_stop_detection->setDisabled(true);
    m_qpushbutton_start_detection->setDisabled(false);
}

void MainWindow::timerLoadImage()
{
    //相机离线测试
    for (int i = 0; i < m_camera_number; i++)
    {
        m_vector_detection_thread[i]->m_image_index++;
        if (m_vector_detection_thread[i]->m_images_path.size() > 0)
        {
            Mat image_read_file;
            image_read_file = imread(m_vector_detection_thread[i]->m_images_path[(m_vector_detection_thread[i]->m_image_index) % m_vector_detection_thread[i]->m_images_path.size()].toLocal8Bit().toStdString());

            if (!image_read_file.empty())
            {
                m_vector_detection_thread[i]->m_camera_index = i;
                m_vector_detection_thread[i]->m_qDisplayFrameQueue.push_back(image_read_file);
            }
        }
    }
}

void  MainWindow::timerPLC()
{
    uint16_t plc_write_value = 1  ;
    if (m_modbus_tcp != nullptr)
        modbus_write_registers(m_modbus_tcp,1100,1,&plc_write_value);
    if (m_modbus_tcp != nullptr)
        modbus_write_registers(m_modbus_tcp,1101,1,&plc_write_value);

    for(int i=1;i< 2;i++)
    {


        uint16_t plc_trigger_value=0;
        if (m_modbus_tcp != nullptr)
            modbus_read_registers(m_modbus_tcp, m_plc_trigger[i], 1, &plc_trigger_value);



        if(1 == plc_trigger_value )
        {
			
//            Sleep(1000);
//			const char* data = "#310FF11";
//			LightSource2.SerialPort->write(data);
			
			
			

            logger->info("read m_plc_trigger:" + std::to_string(m_plc_trigger[i]) + " " +to_string(plc_trigger_value));
            uint16_t plc_write_value = 0  ;
            modbus_write_registers(m_modbus_tcp,m_plc_trigger[i],1,&plc_write_value);
			m_vector_detection_thread[i]->m_detection_times = 0;
            m_vector_camera[i]->softTrigger();
        }
		if (2== plc_trigger_value)
		{
//            Sleep(1000);
//			const char* data = "#310C86A";
//			LightSource2.SerialPort->write(data);

			logger->info("read m_plc_trigger:" + std::to_string(m_plc_trigger[i]) + " " + to_string(plc_trigger_value));
			uint16_t plc_write_value = 0;
			modbus_write_registers(m_modbus_tcp, m_plc_trigger[i], 1, &plc_write_value);
			m_vector_detection_thread[i]->m_detection_times = 1;
			m_vector_camera[i]->softTrigger();
		}

    }

    for(int i=0;i< m_camera_number;i++)
    {
        QString section = "camera" + QString::number(i) + "/";
        QString m_camera_name = m_settings_para->value(section + "m_cameraname", QString::number(i)).toString();
        m_vector_qlabel_show_ok[i]->setText(m_camera_name + "NG:" + QString::number(m_vector_error_number[i]));
        m_vector_qlabel_show_all[i]->setText(m_camera_name + "ALL:" + QString::number(m_vector_all_number[i]));
    }

}

void MainWindow::loadRecipe()
{

    if (m_vector_detection_thread[0]->m_proess_state == true)
    {
         QMessageBox::warning(nullptr, "Title", "停止检测，再设置参数");
         return;
    }


    QString name = m_load_recipe_dialog.getTypeName();
    if( name == "")
    {
        QMessageBox::information(nullptr,"没有选择" , "没有选择");
        return;
    }
    QMessageBox *msgBox = new QMessageBox(QMessageBox::Question,name, name + "重启", QMessageBox::Yes | QMessageBox::No);


    msgBox->button(QMessageBox::Yes)->setText("确认");


    msgBox->button(QMessageBox::No)->setText("退出");

    int res = msgBox->exec();

    if(QMessageBox::Yes == res)
    {

        if(m_modbus_tcp != nullptr)
        {
            modbus_close(m_modbus_tcp);
			modbus_free(m_modbus_tcp);
			m_modbus_tcp = nullptr;
            //delete m_modbus_tcp;

            for (int i = 0; i < m_camera_number; i++)
            {
                if(m_online==1)
                    m_vector_camera[i]->m_camera_interface->camera_end();
            }
            LightSource.SerialPort->close();
//            LightSource2.SerialPort->close();
            logger->info("切换型号");
            Sleep(2000);
        }

        m_settings_para->setValue("para/m_type_name" ,name);
        m_settings_para->sync();

        const QString program = QCoreApplication::applicationFilePath();
        const QStringList arguments = QCoreApplication::arguments();
        const QString directory_now = QDir::currentPath();
        QCoreApplication::exit();
        QProcess::startDetached(program, arguments, directory_now);
    }

}


void MainWindow::initdockShow()
{
    m_qdockwidget_show = new QDockWidget(("数据显示"), this);
    m_qdockwidget_show->setAllowedAreas(Qt::RightDockWidgetArea);
    addDockWidget(Qt::RightDockWidgetArea, m_qdockwidget_show);
    menuBar()->addMenu(("数据显示"))->addAction(m_qdockwidget_show->toggleViewAction());

    QWidget* qwidget = new QWidget();
    m_qdockwidget_show->setWidget(qwidget);

    QVBoxLayout* qvobxlayout = new QVBoxLayout();
    qvobxlayout->setSpacing(30);
    qwidget->setLayout(qvobxlayout);


    m_vector_error_number.resize(m_camera_number);
    m_vector_all_number.resize(m_camera_number);

    QLabel* plabel= nullptr;
    plabel = new QLabel();
    plabel->setText("型号:" + m_type_name);
    plabel->setFixedSize(200, 20);
    qvobxlayout->addWidget(plabel);

    for (int index=0;index<m_camera_number;index++)
    {

        plabel = new QLabel(this);
        QString section = "camera" + QString::number(index) + "/";
        QString m_camera_name = m_settings_para->value(section + "m_cameraname", QString::number(index)).toString();





        plabel = new QLabel();
        plabel->setText(m_camera_name + "OK 0");
        plabel->setFixedSize(200, 20);
        qvobxlayout->addWidget(plabel);
        m_vector_qlabel_show_ok.push_back(plabel);

        plabel = new QLabel();
        plabel->setText(m_camera_name + "ALL 0");
        plabel->setFixedSize(200, 20);
        qvobxlayout->addWidget(plabel);
        m_vector_qlabel_show_all.push_back(plabel);
    }

//    qvobxlayout->addStretch();
}

void MainWindow::saveImage(VectorOutputResult result)
{

	if (result.m_save_right && result.m_detectin_result == true) {
        QString DirName = m_save_image_dir + QDateTime::currentDateTime().toString("/yyyyMMdd/") + m_type_name +"/"+ result.m_camera_name + "/OK/";



		QDir dir;
		if (!dir.exists(DirName))
		{
			dir.mkpath(DirName);
		}
		QString path = DirName + QDateTime::currentDateTime().toString("yyyyMMdd_HHmmss") + ".png";
		m_save_image_thread->addImage(path.toLocal8Bit().toStdString(), result.m_image);
		logger_data->info(path.toStdString());
		logger_data->info(result.m_messgae.toStdString());
	}
	if (result.m_save_wrong && result.m_detectin_result == false) {
        QString DirName = m_save_image_dir + QDateTime::currentDateTime().toString("/yyyyMMdd/") + m_type_name +"/" + result.m_camera_name + "/NG/";

		QDir dir;
		if (!dir.exists(DirName))
		{
			dir.mkpath(DirName);
		}
		QString path = DirName + QDateTime::currentDateTime().toString("yyyyMMdd_HHmmss") + ".png";
		m_save_image_thread->addImage(path.toLocal8Bit().toStdString(), result.m_image);
		logger_data->info(path.toStdString());
		logger_data->info(result.m_messgae.toStdString());
	}

	if (result.m_save_right_label && result.m_detectin_result == true) {
        QString DirName = m_save_image_dir + QDateTime::currentDateTime().toString("/yyyyMMdd/") + m_type_name +"/" + result.m_camera_name + "/OKlabel/";

		QDir dir;
		if (!dir.exists(DirName))
		{
			dir.mkpath(DirName);
		}
		QString path = DirName + QDateTime::currentDateTime().toString("yyyyMMdd_HHmmss") + "label.png";
		m_save_image_thread->addImage(path.toLocal8Bit().toStdString(), result.m_image_draw);
		
	}
	if (result.m_save_wrong_label && result.m_detectin_result == false) {
        QString DirName = m_save_image_dir +QDateTime::currentDateTime().toString("/yyyyMMdd/") + m_type_name +"/"+ result.m_camera_name + "/NGlabel/";

		QDir dir;
		if (!dir.exists(DirName))
		{
			dir.mkpath(DirName);
		}
		QString path = DirName + QDateTime::currentDateTime().toString("yyyyMMdd_HHmmss") + "label.png";
		m_save_image_thread->addImage(path.toLocal8Bit().toStdString(), result.m_image_draw);
		
	};
}
